package com.shorturi.uri.service.impl;

import com.shorturi.uri.service.UriService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author sola
 */
@Slf4j
@Service
public class UriServiceImpl implements UriService {

    @Value("${path.value}")
    @NotNull
    private String pathValue;

    @Value("${ip.address}")
    private String ipAddress;

    @Value("${server.port}")
    private String port;

    /**
     * @return
     */
    @Override
    @Cacheable("ipAddress")
    public String getIpAddress() {
        String ipAddress = pathValue;
        if (!this.ipAddress.isEmpty()) {
            final String projectname = System.getProperty("user.dir");
            final String pn =projectname.substring(projectname.lastIndexOf('\\')+1,projectname.length());
            ipAddress = this.ipAddress + ":" + port +"/"+ pn+"/s/";
        }
        return ipAddress.replace("//","/");
    }


    @Override
    @Cacheable("ipAddress")
    public String getIpAddress2() {
        String ipAddress = pathValue;
        try {
            ipAddress = InetAddress.getLocalHost().getHostAddress() + ":" + 8087;
            log.debug("+++++++++++++缓存过期++++++++++++++");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return ipAddress;
    }
}
